
usage = """

for example:

% python make_middleware.py /tmp/mid/W1200_1400

"""

import os
from whiff import middleware
mroot = "../../whiff/middleware"
template_fn = "middleware_template.whiff"
template_fn_2 = "middleware_template2.whiff"

GET_MODULE_FUNCTION = """
def f():
    import %(parent)s
    try:
        from %(parent)s import %(child)s
    except ImportError:
        # one more time...
        reload(%(parent)s)
        from %(parent)s import %(child)s
    return %(child)s
"""

categories = {
"naming": ("Naming management helpers",1000),
"formatting": ("Data Formatting",2000),
"tools": ("Specialized tools",3000),
"authorization": ("User authorization and management",4000),
"logic": ("Application logic helpers",5000),
"library": ("Support for external libraries",6000),
"ajax": ("Support for AJAX and other advanced functionality", 7000),
"miscellaneous": ("Miscellaneous",8000),
}

def traverse(collector, filenames, mroot=mroot, category="miscellaneous"):
    filepath = os.path.join(mroot, *filenames)
    if os.path.isdir(filepath):
        #print "dir", filenames
        fns = os.listdir(filepath)
        if "whiff.category" in fns:
            fns.remove("whiff.category")
            fpath = os.path.join(filepath, "whiff.category")
            c = file(fpath).read().split()[0].lower()
            if c in categories:
                category = c
            else:
                raise ValueError, "bad category in "+repr((fpath, c))
        fns = [ (x.upper(), x) for x in fns ]
        fns.sort()
        fns = [ y for (x,y) in fns ]
        for fn in fns:
            if fn!="__init__.py":
                traverse(collector, filenames+[fn], mroot, category)
    else:
        #print "file", filenames
        collectorList = collector.get(category, [])
        collector[category] = collectorList
        if filepath.endswith(".py"):
            try:
                mod = import_middleware(filenames)
            except "xxx":
                #print "exception", filenames
                collectorList.append("<br><em>exception "+repr((filenames))+"</em>")
            else:
                #print "mod", mod
                if hasattr(mod, "whiffCategory"):
                    category0 = mod.whiffCategory.lower()
                    if category0 in categories:
                        category = category0
                        collectorList = collector.get(category, [])
                        collector[category] = collectorList
                    else:
                        collectorList.append("<br><em>bad whiffCategory "+repr((filenames, category0))+"</em>")
                if hasattr(mod, "whiffDoc"):
                    collectorList.append(mod.whiffDoc)
                elif hasattr(mod, "skipWhiffDoc"):
                    pass # skip it.
                else:
                    collectorList.append("<br><br><em>no documentation "+repr((filenames))+"</em>")
        elif filepath.endswith(".whiffDoc"):
            #print "whiffDoc", filepath
            text = open(filepath).read()
            collectorList.append(text)
    return collector

def import_middleware(filenames):
    parents = ["whiff.middleware"]+filenames[:-1]
    part = filenames[-1][:-3]
    parent = ".".join(parents)
    defn = GET_MODULE_FUNCTION % {"parent": parent, "child": part}
    exec(defn)
    mod = f()
    return mod

if __name__=="__main__":
    import sys
    prefix = sys.argv[1]
    collector = traverse({}, [])
    D = {}
    D["title"] = "Standard whiff_middleware"
    D["components"] = "" #"\n".join(collector)
    txt = open(template_fn).read()
    mainPage = txt % D
    mainFileName = prefix+".stdMiddleware.whiff"
    print "writing", mainFileName
    file(mainFileName, "w").write(mainPage)
    txt = open(template_fn_2).read()
    for category in collector:
        (title, order) = categories[category]
        components = collector[category]
        D = {}
        D["title"] = title
        D["components"] = "\n\n".join(components)
        catTxt = txt % D
        catPage = "%s_%s.%s.whiff" % (prefix, order, category)
        print "writing", catPage
        file(catPage, "w").write(catTxt)



